package com.boot.security.server.utils.mffl.JPush;

import com.mysql.fabric.xmlrpc.Client;

import java.io.IOException;
import java.io.InputStreamReader;
import java.util.*;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class CommonTools {

    public static String getProperties(String keyName) {
        String keyValues = "";
        try {
            Properties prop = new Properties();
            //InputStream in = CommonTools.class.getResourceAsStream("/messages.properties");
            //InputStream in = CommonTools.class.getResourceAsStream("classpath:applicationContext.xml");
            InputStreamReader in = new InputStreamReader(Client.class.getClassLoader().getResourceAsStream(
                    "messages.properties"), "UTF-8");
            prop.load(in);
            Set keyValue = prop.keySet();
            for (Iterator it = keyValue.iterator(); it.hasNext(); ) {
                String key = (String) it.next();
                if (key.equals(keyName)) {
                    keyValues = prop.getProperty(key);
                    break;
                }
            }
            // 关闭流
            in.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return keyValues;
    }

    /**
     * 生成随机数
     *
     * @param NumCount
     * @return
     */
    public static String CreateRandomNum(int NumCount) {
        String allChar = "0,1,2,3,4,5,6,7,8,9";
        String[] allCharArray = allChar.split(",");// 拆分成数组
        String randomNum = "";
        int temp = -1;// 记录上次随机数的数值，尽量避免产生几个相同的随机数

        Random rand = new Random();
        for (int i = 0; i < NumCount; i++) {
            if (temp != -1) {
                rand = new Random(i * temp * ((int) Calendar.getInstance().getTimeInMillis()));
            }
            int t = rand.nextInt(allCharArray.length);
            if (temp == t) {
                return CreateRandomNum(NumCount);
            }
            temp = t;
            randomNum += allCharArray[t];
        }
        return randomNum;
    }

    /**
     * 按照正则截取字符串
     *
     * @param regex
     * @param source
     * @return
     */
    public static String getMatcher(String regex, String source) {
        String result = "";
        Pattern pattern = Pattern.compile(regex);
        Matcher matcher = pattern.matcher(source);
        while (matcher.find()) {
            result = matcher.group(1);
        }
        return result;
    }

}
